import 'package:flutter/material.dart';
import 'package:osc/data/repository/repository.dart';
import 'package:osc/common/osc_user_manager.dart';
import 'package:osc/models/entity/osc_author.dart';
import 'package:osc/models/entity/osc_base_list_entity.dart';
import 'package:osc/models/entity/osc_tweet_like_list_entity.dart';
import 'package:osc/models/pop_result/pop_result.dart';
import 'package:osc/res/dimens.dart';
import 'package:osc/res/strings.dart';
import 'package:osc/ui/pages/account/login_page.dart';
import 'package:osc/ui/widgets/no_data_widget.dart';
import 'package:osc/ui/widgets/user/osc_portraint_widget.dart';
import 'package:osc/ui/widgets/small_widgets.dart';
import 'package:osc/utils/navigator_util.dart';
import 'package:osc/utils/pd_util.dart';
import 'package:osc/utils/string_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

/// 动弹点赞列表
class TweetLikeList extends StatefulWidget {
  final int id;

  const TweetLikeList({Key key, @required this.id,}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return new TweetLikeListState(id);
  }
}

class TweetLikeListState extends State<TweetLikeList> with AutomaticKeepAliveClientMixin<TweetLikeList> {
  final int id;
  TweetLikeListState(this.id);

  HttpRepository httpRepository;
  String pageToken;
  int size = 0;
  bool isLoadedData = false;

  double paddingParentHorizontal = Dimens.gap_activity_horizontal;
  double paddingChildVertical = Dimens.gap_view_normal;
  double paddingChildHorizontal = Dimens.gap_view_normal;
  double portraitSize = Dimens.view_item_icon_height_bigger;


  List<OscTweetLike> list;

  RefreshController refreshController;

  @override
  void initState() {
    super.initState();
    refreshController = RefreshController(initialRefresh: true);
    httpRepository = HttpRepository();
  }

  @override
  void dispose() {
    super.dispose();
    refreshController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return SmartRefresher(
      controller: refreshController,
      onRefresh: refresh,
      onLoading: loadMore,
      enablePullUp: true,
      child: ListView.separated(
        itemBuilder: (BuildContext context, int index) {
          if (size == 0) {
            return NoDataWidget();
          } else {
            return buildListItem(index);
          }
        },
        separatorBuilder: (BuildContext context, int index) {
          return SmallWidgets.buildLine();
        },
        itemCount: isLoadedData && size == 0? 1 : size,
      ),
    );
  }

  buildListItem(int index){
    OscTweetLike item = list.elementAt(index);
    return Container(
      padding: EdgeInsets.only(left: paddingParentHorizontal, right: paddingParentHorizontal, top: paddingParentHorizontal, bottom: paddingParentHorizontal),
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          buildUser(item.author),
        ],
      ),
    );
  }

  buildUser(OscAuthor author){
    return Padding(
      padding: EdgeInsets.only(bottom: paddingChildVertical),
      child: Row(
        children: <Widget>[
          OscPortraitWidget(id: author.id, portraitImageUrl: author.portrait, size: Dimens.view_item_icon_height_big,),
          Padding(
            padding: EdgeInsets.only(left: paddingChildHorizontal),
            child: buildText(author.name, Colors.black, Dimens.font_sp14),
          ),
        ],
      ),
    );
  }


  buildText(String data, Color color, double fontSize) {
    return SmallWidgets.buildText(data, color, fontSize);
  }

  Future<Null> refresh() async{
    pageToken = null;
    list?.clear();
    return await loadMore();
  }


  Future<Null> loadMore() async{
    isLoadedData = true;
    await httpRepository.getTweetLikeList(tweetId: id, pageToken: pageToken).then((resp){
      if(resp != null && resp.success){
        OscBaseListResult result = resp.result;
        if(result != null){
          List<OscTweetLike> tempList = result.items;
          if(StringUtil.isEmpty(pageToken)){
            list = tempList;
          } else {
            list.addAll(tempList);
          }
          size = list?.length??0;
          pageToken = result.nextPageToken;
          if(result.requestCount > result.responseCount){
            refreshController.loadNoData();
          } else {
            refreshController.loadComplete();
          }
        }
      }
    });
    setState(() {
      refreshController.refreshCompleted();
    });
  }

  jump2PageForResult(Widget page, {bool checkLogin = false}) {
    if(checkLogin){
      if(OscUserManager.getInstance().isLogin()){
        jumpToPageForResult(page);
      } else {
        jumpToPageForResult(LoginPage());
        showTips(StringIds.userNoLogin);
      }
    } else {
      jumpToPageForResult(page);
    }
  }
  jumpToPageForResult(Widget page) {
    NavigatorUtil.pushPageForResult<PopResult>(context, page).then((result) {
      if (result != null) {
        switch (result.id) {
          case PopResult.ID_LOGIN:
            break;
        }
      }
    });
  }

  showTips(String msg){
    PdUtil.showToast(msg: msg);
  }

  @override
  bool get wantKeepAlive => true;
}
